package com.jeegot.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeegot.mall.entity.DeliveryAddress;
import com.jeegot.mall.mapper.DeliveryAddressMapper;
import com.jeegot.mall.service.IDeliveryAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 收货地址 服务实现类
 * </p>
 *
 * @author wjun_java@163.com
 * @since 2021-06-18
 */
@Service
public class DeliveryAddressServiceImpl extends ServiceImpl<DeliveryAddressMapper, DeliveryAddress> implements IDeliveryAddressService {

	@Override
	public List<DeliveryAddress> getUserAddress(Long userId) {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("user_id", userId);
		return list(queryWrapper);
	}

	@Override
	@Transactional
	public DeliveryAddress saveAddress(DeliveryAddress deliveryAddress, Long userId) throws Exception {
		if(deliveryAddress.getId() == null) deliveryAddress.setUserId(userId);
		if(deliveryAddress.getIsDefault()) {
			List<DeliveryAddress> userAddressList = getUserAddress(userId);
			userAddressList.forEach(item -> item.setIsDefault(false));
			saveOrUpdateBatch(userAddressList);
		}
		saveOrUpdate(deliveryAddress);
		return deliveryAddress;
	}

	@Override
	public DeliveryAddress getDefault(Long userId) {
		List<DeliveryAddress> deliveryAddressList = getUserAddress(userId);
		List<DeliveryAddress> defaultAddressList = deliveryAddressList.stream().filter(item -> item.getIsDefault() == true).collect(Collectors.toList());
		if(defaultAddressList != null && defaultAddressList.size()>0) {
			return defaultAddressList.get(0);
		}

		if(deliveryAddressList != null && deliveryAddressList.size()>0) {
			return deliveryAddressList.get(0);
		}

		return null;
	}

}
